var tbKeyArr = [];
var tbMap = {};//定义数据字典类型表格对象集合
var tbObjMap = {};
var dialogList = {};//定义数据字典详情页面对象集合
var dialogMap = {};//定义数据字典详情页面对象集合
var ruleMap = {};//定义规规则对象集合

var active_key = "t_dictionary_country";//定义当前选中的字典类型
var active_tbObj = null;
var active_dialog = null;
var tbDataUrl = "/system/dataDic/queryList";

var is_add = true;//定义是否新增变量
var seachKeys = {};
var dicStr = "";
<#list configer as itemOut>
	dicStr = dicStr + "${itemOut.tableCode};";
	
	<#list itemOut.tableConfigers as itemIn>
		<#if (itemIn.columnKey!"defaultValue") == "PRI">seachKeys['${itemIn.tableName}'] = "${itemIn.columnName}";<#else ></#if>
	</#list>
</#list>

/**判断是否需要重新生成HTML和JS开始**/
$.ajax({
    type: 'GET',
    url: '/system/dataDic/init',
    data:{
    	dicStr:dicStr,
    	token:sessionStorage.token
    },
    async: false,
    success:function(data) {
        //_self.goodsList = data;
	    data= data.resultData;
		if(data['isCreate']){
			//location.reload();
		}
	}
});
/**判断是否需要重新生成HTML和JS结束**/
/**初始化赋值变量开始**/
$.ajax({
    type: 'GET',
    url: '/system/dataDic/queryConfig',
    data:{
    	token:sessionStorage.token
    },
    async: false,
    success:function(data) {
        //_self.goodsList = data;
	    data= data.resultData;
		//初始化赋值
		var tbKey = "";
		var tbConfig = {};
		var columnArr = [];
		for(var i=0;i<data.length;i++){
			if(tbKey!=data[i]['tableName']){
				if(tbKey!=""){
					tbConfig['columns']=columnArr;
					tbObjMap[tbKey] = tbConfig;
				}
				tbConfig = {};
				columnArr = [];
				tbConfig['tableSchema'] = data[i]['tableSchema'];
				tbConfig['tableName'] = data[i]['tableName'];
				columnArr.push(data[i]);
				tbKey = data[i]['tableName'];
				tbKeyArr.push(tbKey);
			}else if(i==data.length-1){
				columnArr.push(data[i]);
				tbConfig['columns']=columnArr;
				tbObjMap[tbKey] = tbConfig;
			}else{
				columnArr.push(data[i]);
			}
		}
	}
});
/**初始化赋值变量结束**/

$(function() {
    //初始化
    Begin();
})
/**定义检验规则类开始**/
<#list configer as itemOut>
	<#list itemOut.tableConfigers as itemIn>
		var ${itemIn.tableName}_${itemIn.columnName} = function(rule, value, callback) {
			
			if(!value.length>${itemIn.characterMaximumLength}) {
				return callback(new Error('超过最大长度！'));
			}
			
			<#if (itemIn.isNullable!"defaultValue") == "NO">
				if(!value) {
					return callback(new Error('请输入${itemIn.columnComment}!'));
				}
			<#else >
			</#if>
			<#if (itemIn.columnKey!"defaultValue") == "PRI">
				if(is_add){
					$.ajax({
					    type: 'GET',
					    url: '/system/dataDic/isRepeat',
					    data:{
					    	tableCode:'${itemIn.tableName}',
					    	field:'${itemIn.columnName}',
					    	val:value,
					    	token:sessionStorage.token
					    },
					    async: false,
					    success:function(data) {
					    	data = data.resultData;
							if(data.isRepeat){
								return callback(new Error('输入${itemIn.columnComment}重复!'));
							}
						}
					});
				}
			<#else >
			</#if>
			return callback();
		};
	</#list>
</#list>
/**定义检验规则类结束**/
var dataReturnObj = {};
var formRules = {};
<#list configer as itemOut>
	var ${itemOut.tableCode}Form = {};
	<#list itemOut.tableConfigers as itemIn>
		${itemIn.tableName}Form['${itemIn.tableName}_${itemIn.columnName}'] = '';
		var ${itemIn.columnName} = [];
		var ${itemIn.columnName}_0 = {};
		${itemIn.columnName}_0['required']=true;
		${itemIn.columnName}_0['validator']=${itemIn.tableName}_${itemIn.columnName};
		${itemIn.columnName}_0['trigger']='blur';
		${itemIn.columnName}.push(${itemIn.columnName}_0);
		formRules['${itemIn.tableName}_${itemIn.columnName}']=${itemIn.columnName};
	</#list>
	dataReturnObj['${itemOut.tableCode}Form'] =${itemOut.tableCode}Form;
</#list>
dataReturnObj['rules'] = formRules;
dataReturnObj['dialogVisible'] = true;
dataReturnObj['disabledInput'] = false;

var dialogInfos = new Vue({
	el: "#dialogInfos",
	data: function() {
		return dataReturnObj;
	},
	methods: {
		submitForm: function(formName) {
			var self = this;
			var params = self[active_key+'Form'];
			var optType = "1";
			if(!is_add){
				optType = "2";
			}
			var keys = "";
    		var fields = "";
    		var cols = tbObjMap[active_key].columns; 
    		for(var i=0;i<cols.length;i++){
    			if(cols[i]['columnKey']=='PRI'){
    				if(!is_add){
    					keys = keys + cols[i]['columnName']+":"+params[active_key+'_'+cols[i]['columnName']]+";";
    				}else{
    					fields = fields + cols[i]['columnName']+":"+params[active_key+'_'+cols[i]['columnName']]+";";
    				}
    			}else{
    				if(cols[i]['columnName']=='isAvaliable'){
    					fields = fields + cols[i]['columnName']+":1;";
    				}else{
    					fields = fields + cols[i]['columnName']+":"+params[active_key+'_'+cols[i]['columnName']]+";";
    				}
    				
    			}
    		}
    		editDic(optType,keys,fields);
			this.dialogVisible = false;
		},
		resetForm: function(formName) {
			this.$refs[formName].resetFields();
		}, //重置
		cancelForm: function(formName) {
			this.dialogVisible = false;
		},
		handleClose:function(){
			this.dialogVisible = false;
		}
	}
});
dialogInfos.dialogVisible = false;

var vanytree = new Vue({
    el: "#treeLeft",
    data: function() {
        return {
            filterText: "",
            title: "",
            icon: "",
            rightIcon: "",
            contexts: "",
            justLeft: true,
            defaultExpandedKeys: [],
            data: [],
            defaultProps: {
                children: '',
                label: 'tableName',
                id: 'tableCode'
            }
        }
    },
    methods: {
        getData: function(params) {
            VanyAjax("/system/dataDic/queryDic",{},"GET").done(function(data) {
                this.defaultExpandedKeys = data.map(function(item) {
                    return item.tableCode;
                });
                this.data = data;
            }, false, this);
        },
        isEmptyTree: function() {
            return this.data.length === 0;
        },
        filterNode: function(value, data) {
            if(!value) return true;
            return data[this.defaultProps.label].indexOf(value) !== -1;
        },
        handleNodeClick: function(data, node, nodeComponent) {
        	active_key = data['tableCode'];
        	for(var i=0;i<tbKeyArr.length;i++){
        		$("#"+tbKeyArr[i]+"Tb").removeClass("activeTb");
    	        $("#"+tbKeyArr[i]+"Tb").addClass("displayTb");
    	        $("#"+tbKeyArr[i]+"Form").removeClass("activeTb");
    	        $("#"+tbKeyArr[i]+"Form").addClass("displayTb");
        	}
    		$("#"+active_key+"Tb").removeClass("displayTb");
            $("#"+active_key+"Tb").addClass("activeTb");
            $("#"+active_key+"Form").removeClass("displayTb");
            $("#"+active_key+"Form").addClass("activeTb");
        	sm.getData();
        },
        // TODO
        resizeTree: function() {

        },
        handleCommand: function(command) {
            
        },
        rightIconClick: function() {
            
        },
        hasPre: function(nodeObj, nodeData) {
            
        },
        hasNext: function(nodeObj, nodeData) {
            
        },
        showContexts: function(isShow) {
           
        },
        renderContent:function(){
        	
        }
    },
    mounted: function() {
        /*this.$el.onmouseover = function(e) {
        	console.log(e);
        }*/
    },
    watch: {
        filterText: function(val) {
            this.$refs.tree.filter(val);
        }
    }
});
vanytree.getData();


var msg = [];
var sm = new Vue({
    el: "#tableR",
    data: function () {
        return {
            loading:false,
            keyword: '',
            tableData: [],
            total: 0,
            pageSize: 10,
            pageIndex: 1,
            sels: [],
            visible: true
        }
    },
    methods: {
        search: function () {
            this.getData(1, this.pageSize, this.keyword);
        },
        editDic: function (row) {
        	is_add = false;
        	dialogInfos.dialogVisible = true;
        	dialogInfos.disabledInput = true;
        	var cols = tbObjMap[active_key].columns;
        	for(var i=0;i<cols.length;i++){
        		dialogInfos[active_key+'Form'][active_key+'_'+cols[i]['columnName']] = row[cols[i]['columnName']];
        		if(cols[i]['columnKey']=='PRI'){
         			$("#"+active_key+'_'+cols[i]['columnName']).disabled = true;
        		}
        	}
        },        
        deleteDic: function(row){
        	msg = row;
        	this.$confirm('确认删除该所选字典信息？', '提示', {
        		confirmButtonText: '确定',
        		cancelButtonText: '取消',
        		type: 'warning'
        	}).then(function() {
        		var keys = "";
        		var fields = "";
        		var cols = tbObjMap[active_key].columns; 
        		for(var i=0;i<cols.length;i++){
        			if(cols[i]['columnKey']=='PRI'){
        				keys = keys + cols[i]['columnName']+":"+msg[cols[i]['columnName']]+";";
        			}
        		}
        		editDic('3',keys,fields);
        	}).catch(function() {})
        },
        addDic: function () {
            dialogInfos.dialogVisible = true;
            dialogInfos.disabledInput = false;
            is_add = true;
            var cols = tbObjMap[active_key].columns;
        	for(var i=0;i<cols.length;i++){
        		dialogInfos[active_key+'Form'][active_key+'_'+cols[i]['columnName']] = '';
        	}
        },
        getData: function (pageIndex, pageSize, keyword) {
            var keywordStr ="";
        	if(keyword&&keyword!='')
        		keywordStr = seachKeys[active_key]+":"+keyword;
            VanyAjax(tbDataUrl, {
                pageIndex: pageIndex,
                pageSize: pageSize,
                searchValue: keywordStr,
                value1:active_key,
                token:sessionStorage.token
            }, "GET").done(function (data) { 
                this.currentPage = data.pageNum;
                this.pageSize = pageSize;
                this.total = data.total;
                var msgs = data.rows;
                this.tableData = msgs;
                
            }, false, this);
        },

        handleCurrentChange: function (val) {
        	this.pageIndex = val;
            this.getData(val, this.pageSize, this.keyword);
        },

        handleSelectionChange: function (selection) {
            this.sels = selection;
        },

        handleSizeChange: function(val){
        	this.pageSize = val;
            this.getData(this.pageIndex, val, this.keyword);
        }
    },
    mounted: function () {
    	var self = this;
		this.$el.style.left = "176px";
		this.tableHeight = window.innerHeight - 320;
        this.getData(this.pageIndex, this.pageSize, this.keyword);
    },
})

/**定义公共函数开始**/
/**增删改方法
 * optType[1:add;2:update;3:delete]
 * **/
function editDic(optType,keys,fields){
	var editParam = {
		tableCode : active_key,
		optType : optType,
		fields: fields,
		keys:keys
	};
	VanyAjax("/system/dataDic/editDic", editParam, "GET").done(function (data) { 
		sm.getData();
    }, true, this);
}


/**定义公共函数结束**/


//初始化
function Begin() {
    //面包屑
    new Vue().$mount('#crumbs');
    sessionStorage.Jurisdiction = "base_tag_addBaseRootTag,base_team_delTeamUsesr,base_user_update,base_tag_modifyBaseTag,base_team_modify,base_role_modifyRFAAndRemove,base_tagUser_export,base_customerUser_export,base_role_modifyRoleInfo,base_customer_import,base_org_delete,base_customer_addTag,base_team_delete,base_org_export,base_role_modifyRoleUser,base_user_resetUserStatus,base_org_import,base_user_export,base_tag_modifyTag,base_customer_add,base_customer_modifyTag,base_user_resetUserPassword,base_user_import,base_team_addTeamUsers,base_tag_deleteTag,base_user_deleteUsers,base_org_update,base_role_deleteRoleUser,base_user_moveUsers,base_teamUser_export,base_tag_addBaseTag,base_team_add,base_tag_selectTagUser,base_tag_addTag,base_customer_delCustomer,base_customer_addRootTag,base_tag_addRootTag,base_org_add,base_user_updateOrderNum,base_tag_deleteTagUser,base_tag_deleteBaseTag,base_customer_deleteTag,base_org_updateOrderNum,base_user_add"

}